package com.teach.javafxclient.controller.base;

import com.teach.javafxclient.Globalvar;
import com.teach.javafxclient.MainApplication;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.text.Text;
import kong.unirest.HttpResponse;
import kong.unirest.JsonNode;
import kong.unirest.Unirest;
import kong.unirest.json.JSONObject;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;

/**
 * LoginController 登录交互控制类 对应 base/login-view.fxml
 *  @FXML  属性 对应fxml文件中的 fx:id 属性 如TextField usernameField 对应 fx:id="usernameField"
 *  @FXML 方法 对应于fxml文件中的 on***Click的属性  如onLoginButtonClick() 对应onAction="#onLoginButtonClick"
 */
public class LoginController {
    @FXML
    public Button loginButton;
    @FXML
    private TextField usernameField;
    @FXML
    private TextField passwordField;
    @FXML
    private Text tip;
    private Integer tryNum = 0;

    /**
     * 页面加载对象创建完成初始话方法，页面中控件属性的设置，初始数据显示等初始操作都在这里完成，其他代码都事件处理方法里
     */
    @FXML
    public void initialize() {
//        usernameField.setText("root");
        usernameField.setText("20249999");
//        usernameField.setText("2022030001");
        passwordField.setText("root");
    }

    /**
     *  点击登录按钮 执行onLoginButtonClick 方法 从面板上获取用户名和密码，请求后台登录服务，登录成功加载主框架，切换舞台到主框架，登录不成功，提示错误信息
     */
    @FXML
    protected void onLoginButtonClick() {
        String username = usernameField.getText();
        String password = passwordField.getText();
//        if(username.matches("^(\\d{8}|\\d{12})$")&&password.matches("^(?=.*[0-9])(?=.*[a-zA-Z])[a-zA-Z0-9]{8,}$")) {
        HttpResponse<JsonNode> res =  Unirest.post(Globalvar.baseUrl+"/api/login")
                .field("id", username)
                .field("password", password)
                .asJson();
        if(res.getStatus() != 200){
            tip.setText("登录失败，请重试");
            System.out.println(res.getStatus());
            return;
        }
        String desktopPath = System.getProperty("user.home") + System.getProperty("file.separator") + "Desktop";
        // 完整的文件路径
        String filePath = desktopPath + System.getProperty("file.separator") + "smsFile" + System.getProperty("file.separator") + "timestamp.txt";

        // 创建smsFile文件夹（如果不存在）
        Path smsFilePath = Paths.get(desktopPath, "smsFile");
        if (!Files.exists(smsFilePath)) {
            try {
                Files.createDirectories(smsFilePath);
            } catch (IOException e) {
                e.printStackTrace();
                System.err.println("Failed to create directory smsFile on desktop.");
                return;
            }
        }

        // 获取当前时间的时间戳
        long timestamp = Instant.now().toEpochMilli();

        // 写入时间戳到文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            writer.write(Long.toString(timestamp));
            System.out.println("时间戳已成功保存到文件：" + filePath);
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("写入文件时出错：" + e.getMessage());
        }


            System.out.println(((JsonNode)res.getBody()).getObject());
            Globalvar.userRole = (String)((JSONObject)((JsonNode)res.getBody()).getObject().get("user")).get("userType");
            Globalvar.userName = (String)((JSONObject)((JsonNode)res.getBody()).getObject().get("user")).get("name");
            Globalvar.specificId = (((JSONObject) ((JsonNode) res.getBody()).getObject().get("user")).get("specificId")) instanceof Long ? ((Long)((JSONObject) ((JsonNode) res.getBody()).getObject().get("user")).get("specificId")) : ((Integer)((JSONObject) ((JsonNode) res.getBody()).getObject().get("user")).get("specificId")).longValue();
            Globalvar.userToken = (String)((JsonNode)res.getBody()).getObject().get("token");
            Globalvar.setCurrentTerm((JSONObject) ((JsonNode)res.getBody()).getObject().get("currentTerm"));
//            System.out.println(Globalvar.currentTerm.get("name"));
            FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("base/main-frame.fxml"));
            try {
                Scene scene = new Scene(fxmlLoader.load(), 1900, 1080);
                Globalvar.MFC = fxmlLoader.getController();
                MainApplication.resetStage("教学管理系统", scene);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
//        }
//        else {
//            tryNum += 1;
//            tip.setText("❗  学工号或密码格式错误，请重试 ×"+tryNum);
//        }
    }


    public void reLoginButtonClick() {
        String username = usernameField.getText();
        String password = passwordField.getText();
//        if(username.matches("^(\\d{8}|\\d{12})$")&&password.matches("^(?=.*[0-9])(?=.*[a-zA-Z])[a-zA-Z0-9]{8,}$")) {
        HttpResponse res =  Unirest.post(Globalvar.baseUrl+"/api/login")
                .field("id", username)
                .field("password", password)
                .asJson();
        if(res.getStatus() != 200){
            tip.setText("登录失败，请重试");
            System.out.println(res.getStatus());
            return;
        }
        String desktopPath = System.getProperty("user.home") + System.getProperty("file.separator") + "Desktop";
        // 完整的文件路径
        String filePath = desktopPath + System.getProperty("file.separator") + "smsFile" + System.getProperty("file.separator") + "timestamp.txt";

        // 创建smsFile文件夹（如果不存在）
        Path smsFilePath = Paths.get(desktopPath, "smsFile");
        if (!Files.exists(smsFilePath)) {
            try {
                Files.createDirectories(smsFilePath);
            } catch (IOException e) {
                e.printStackTrace();
                System.err.println("Failed to create directory smsFile on desktop.");
                return;
            }
        }

        // 获取当前时间的时间戳
        long timestamp = Instant.now().toEpochMilli();

        // 写入时间戳到文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            writer.write(Long.toString(timestamp));
            System.out.println("时间戳已成功保存到文件：" + filePath);
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("写入文件时出错：" + e.getMessage());
        }


        System.out.println(((JsonNode)res.getBody()).getObject());
        Globalvar.userRole = (String)((JSONObject)((JsonNode)res.getBody()).getObject().get("user")).get("userType");
        Globalvar.userName = (String)((JSONObject)((JsonNode)res.getBody()).getObject().get("user")).get("name");
        Globalvar.specificId = (Long) ((JSONObject)((JsonNode)res.getBody()).getObject().get("user")).get("specificId");
        Globalvar.userToken = (String)((JsonNode)res.getBody()).getObject().get("token");
        Globalvar.setCurrentTerm((JSONObject) ((JsonNode)res.getBody()).getObject().get("currentTerm"));
//            System.out.println(Globalvar.currentTerm.get("name"));
//        }
//        else {
//            tryNum += 1;
//            tip.setText("❗  学工号或密码格式错误，请重试 ×"+tryNum);
//        }
    }
}